<?php
require_once (__DIR__ . "/../inc/functions.php");
require_once (__DIR__ . "/Keywords.php");

class addresses
{
	static function GetAll()
	{
		$conn = GetConnection();
		$results=$conn->query('SELECT * FROM addresses');
		$error=$conn->error;		
		return $results; 
		
	}
	
	static function Get($id)
	{
		$conn = GetConnection();
		$results = $conn->query("SELECT * FROM addresses WHERE id=$id");
		$row = $results->fetch_assoc();
		$error=$conn->error;
		return $row;
	}
	
	static function GetForUser($userid)
	{
		$conn = GetConnection();
		$results = $conn->query("SELECT * FROM addresses WHERE userId=$userid");
		$error=$conn->error;	
//		print_r($error);	
		return $error != '' ? false : $results;
	}
	
	static function GetAddressType($id)
	{
		$row = keywords::Get($id);
		return $row['name'];
	}
	
	static function Insert($row)
	{
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);
		$sql = 	"INSERT INTO addresses (AddressType,line_1,line_2,city,state,zip,userId) "
			.	"Values ($row2[addressType],'$row2[line_1]','$row2[line_2]','$row2[city]','$row2[state]',$row2[zip],$row2[userId]); ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Update($row)
	{
		//print_r ($row);	
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);
		$sql = 	"UPDATE addresses "
			.	"Set addressType=$row2[addressType],line_1='$row2[line_1]',line_2='$row2[line_2]',city='$row2[city]',state='$row2[state]',zip=$row2[zip],userId=$row2[userId] "
			.	"WHERE id=$row2[id] ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Delete($id)
	{
		$conn = GetConnection();
		$sql = 	"DELETE FROM addresses "
			.	"WHERE id=$id ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;				
	}
	static function Validate($row)
	{
		$results = array();
		if(empty($row['line_1'])) $results['line_1'] = 'Line 1 is required';		
		if(empty($row['line_2'])) $results['line_2'] = 'Line 2 is required';		
		if(empty($row['city'])) $results['city'] = 'City is required';		
		if(empty($row['state'])) $results['state'] = 'State is required';		
		if(empty($row['zip'])) $results['zip'] = 'Zip is required';		
		if(!is_numeric($row['zip'])) $results['zip'] = 'Zip must be a number';		
		
		return count($results) > 0 ? $results : true;
	}
	
}

?>
